#!/usr/bin/env node

const arg= process.argv.slice(2),
  fs= require('fs'),
  path = require('path');

//一个参数
if(arg.length == 1){
  //list
  if(arg[0] == '-list'){

    let pathName = './sysFile';
    let files = fs.readdirSync('sysFile');
    let dirs = [];
    for(var i= 0;i< files.length;i++){
 
      let fname = `${pathName}/${files[i]}`;  
      let data = fs.statSync(fname);
      var obj = {};

      obj.fileName = files[i];
      obj.size = data.size;
      obj.createTime = data.birthtimeMs;
        
      dirs.push(obj);
    }
    sortTime(dirs);
    timeTransform(dirs);
    let dirJson = JSON.stringify(dirs,',',2);
    console.log(dirJson);
  }
  else{
    console.error('length = 1 but wrong!');
  }
}else if(arg.length == 2){
  //show
  if(arg[0] == '-show'){
    //console.log('show'); 
    const fileName = `./sysFile/${arg[1]}`;
    if(fs.existsSync(fileName)){
      console.log(fs.readFileSync((fileName),'utf8'));    
    }else{
      console.error('not exists');
    }
  }
  //delete
  else if(arg[0] == '-del'){
    // console.log('del');
    const fileName = `./sysFile/${arg[1]}`;
    
    if(fs.statSync(fileName).isDirectory()){
      deleteDir(fileName);
      console.log('删除成功');
      process.exit(1);
    }
    if(fs.statSync(fileName).isFile()){
      fs.unlinkSync(fileName);
      console.log('删除成功');
      process.exit(1);
    }
    else{
      console.error('文件不存在');
    }
  }else{
    console.error('length = 2 but wrong');
  }
}else{
  console.error('length > 3 wrong!');
}

function sortTime(arr){
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < i ;j++){
      let temp = [];
      if(arr[i].createTime < arr[j].createTime){
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  } 
}

function timeTransform(arr){
  //console.log(time);
  for(var i =0;i < arr.length ;i++){
    let t = new Date(arr[i].createTime);
    //console.log('t:',t);
    var year = t.getFullYear();
    var month = t.getMonth()+1;
    var day = t.getDate();
    var hour = t.getHours();
    var min = t.getMinutes();
   
    var d = `${year}-${month}-${day} ${hour}:${min}`;
    arr[i].createTime = d;
  }
}

function deleteDir(src){
  let files = fs.readdirSync(src);
  files.forEach(function(file,index){
    var cPath = path.join(url,file);
    if(fs.statSync(cPath).isDirectory()){
      deleteDir(cPath);
    }else{
      fs.unlinkSync(cPath);
    }
  });
  fs.rmdirSync(src);
}
